<?php
/*

  Template Name: Register

 */

get_template_part('secondary', 'header');
get_template_part('secondary', 'sidebar');

global $post, $wpdb;

setup_postdata($post);

$post_id = $post->ID;

$user = wp_get_current_user();
$user_id = $user->ID;

$year = date('Y');
$month = date('m');

function startsWith($haystack, $needle) {
    $length = strlen($needle);
    return (substr($haystack, 0, $length) === $needle);
}

?>

<script>
    jQuery(document).ready(function(){
        jQuery("#savings_cbo").change(function(){
            jQuery("#savings_text").val(jQuery(this).val());
        });
    });
</script>


<div id="dash-content">

    <div class="post-content">

        <header>

            <nav>
                <div class="puntuacion">
                    <span>Valora esta BPA marcando las estrellas </span>
                    <br>
                        <?php echo the_ratings('span', get_the_ID(), false); ?>
                    <br>
                    <span>OJO. Una vez emitido tu voto no podrás cambiarlo. ¡Piénsalo bien!<br> Muchas gracias.</span>
                </div>
                <div class="share">
                    <?php echo do_shortcode('[addtoany]'); ?>
                </div>
            </nav>

            <h2><?php the_title(); ?></h2>

        </header> 

        <figure>
            <?php
                if (has_post_thumbnail()) {
                    the_post_thumbnail(array('600', '276'));
                }
            ?>
        </figure>

        <h3>Descripción</h3>

        <p><?php the_content(); ?></p>
        <h3>Metodología</h3>

        <p><?php echo get_post_meta(get_the_ID(), '_bpa_metodology', true); ?></p>
        <div id="separacion"></div>
        <div class="cuatro-cajas">
            <h3>
                Monto de inversión
                <br><span class="referencial">referencial</span>
            </h3>
            <?php echo get_post_meta(get_the_ID(), '_bpa_amount', true); ?>
        </div>

        <div class="cuatro-cajas">
            <h3>Retorno en meses
            <br><span class="referencial">referencial</span>
            </h3>

            <?php echo get_post_meta(get_the_ID(), '_bpa_returns', true); ?>
        </div>

        <div class="clear"></div>
            
        <?php

            $type_id = 0;
            $terms = wp_get_post_terms(get_the_ID(), 'tipo-consumo', array("fields" => "slugs"));
            if (in_array('agua', $terms)) {
                $type_id = 1;
            } elseif (in_array('energia', $terms)) {
                $type_id = 2;
            }
            
            $basic_devices_data = $wpdb->get_results($wpdb->prepare(
                                "select bd.*, 
                                it.type_id , it.name as item_name, it.full_name as item_full_name, 
                                iu.quantity
                                from bpa_saving_basic_device bd
                                left join bpa_inventory_item it
                                on bd.item_id = it.id
                                left join bpa_inventory_user iu
                                on it.id = iu.item_id
                                where bd.post_id = %d
                                and it.type_id = %d
                                and iu.user_id = %d", $post_id, $type_id, $user_id));

            $inventory_total = $wpdb->get_var($wpdb->prepare(
                                "select sum(iu.quantity)
                                from bpa_saving_basic_device bd
                                left join bpa_inventory_item it
                                on bd.item_id = it.id
                                left join bpa_inventory_user iu
                                on it.id = iu.item_id
                                where bd.post_id = %d
                                and it.type_id = %d
                                and iu.user_id = %d", $post_id, $type_id, $user_id));
            
            $price = $wpdb->get_var($wpdb->prepare("select price from bpa_consumption_type where id = %d", $type_id));
            
            $workers = $wpdb->get_var($wpdb->prepare(
                                    "select number
                                    from bpa_registry_workers w
                                    where w.user_id = %d
                                    and year = %d
                                    and month = %d", $user_id, $year, $month));
            
            if($basic_devices_data) {
        ?> 
            <div class="cuatro-cajas">
                <h3>Monto de ahorro
                <br><span class="referencial">referencial</span>
                </h3>

                <?php
                
                    if($inventory_total == 0) {
                        
                        echo "Si desea que le mostremos los montos que podría ahorrar por favor registre sus equipos en el Inventario dentro de su Perfil";
                        
                    }else {

                        foreach ($basic_devices_data as $basic_device) {

                            $item_name = $basic_device->item_full_name ? $basic_device->item_full_name : $basic_device->item_name;

                            $usage = $basic_device->average_use ? $basic_device->average_use : 0;
                            $consumption_per_time = $basic_device->consumption_per_time ? $basic_device->consumption_per_time : 0;
                            $quantity = $basic_device->quantity ? $basic_device->quantity : 0;

                            if($quantity == 0){
                                continue;
                            }

                ?>            

                            <div class="basic-device">
                                <h4><?php echo $item_name; ?></h4>
                                <div class="saving-devices-list">
                                    <?php 
                                        $saving_devices = $wpdb->get_results($wpdb->prepare(
                                                "select ad.basic_device_id, sit.name, ad.saving_ratio 
                                                from bpa_saving_alternative_device ad
                                                left join bpa_saving_item sit
                                                on ad.saver_item_id = sit.id
                                                where basic_device_id = %d", $basic_device->id));

                                        if ( $saving_devices ) {
                                            foreach ( $saving_devices as $saving_device ) {
                                                $saving_ratio = $saving_device->saving_ratio;
                                                $saving_value = 0;
                                                if ($type_id == 1){
                                                    $saving_value = $usage * $consumption_per_time * $price * $saving_ratio * $workers;
                                                } elseif ($type_id == 2){

                                                    $saving_value = $usage * $consumption_per_time * $price * $saving_ratio * $quantity;
                                                } 
                                                $saving_value = number_format((float)$saving_value, 2, '.', '');
                                    ?>
                                                <div>
                                                <ul><li> <?php echo $saving_device->name.": <ul><li><span style='color: #07a000; font-weight:bold;'>S/.".$saving_value."</span></li></ul>"; ?></li></ul>
                                                </div>  
                                    <?php
                                            }
                                        } else {
                                            echo "<div>".$basic_device->description."</div>";
                                        }

                                    ?>
                                </div>
                                <br/>
                            </div>

                <?php   }
                
                    }
                
                ?>

            </div>
        
        <?php } ?>

        <div class="cuatro-cajas">
            <h3>Contacto</h3>
            <p>Si tienes alguna pregunta o recomendación <a href="mailto:contacto@ecopyme.pe " class="green">escríbenos</a></p>
        </div>

        <div class="cuatro-cajas"><hr></div>
        <div class="cuatro-cajas"><hr></div>
        <div style="clear:both"></div>
        
        <h3>Proveedores</h3>

        <ul class="proveedores-list">

            <?php
                $providers = get_post_meta(get_the_ID(), '_bpa_providers', true);

                if ($providers != "") {

                    foreach ($providers as $provider_id) {
                        $ppost = get_post($provider_id);
            ?>

                            <li>
                                <h4><?php echo $ppost->post_title; ?></h4>
                                <?php
                                    $email = get_post_meta($ppost->ID, '_provider_email', true);
                                    $originalemail = $email;
                                    if (strpos($email, '@') !== false) {
                                        $email = "mailto:" . $email;
                                    } elseif (startsWith($email, "http")) {
                                    } else {
                                        $email = "http://" . $email;
                                    }
                                ?>
                                <a href="<?php echo $email; ?>" class="green"><?php echo $originalemail; ?></a>
                                <span><?php echo get_post_meta($ppost->ID, '_provider_phone', true); ?></span>
                            </li>
             <?php  
                    }
                }
             ?>

        </ul>

    </div>

</div>

<?php get_template_part('secondary', 'footer'); ?>